﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace JMT.Data
{
    public sealed class JContainer<T> : IJContainer<T> where T : IJModel
    {
        private List<JContainerUpdate<T>> _update;

        ObservableCollection<T> _collection;
        public JContainer()
        {
            _update = new List<JContainerUpdate<T>>();

            _collection = new ObservableCollection<T>();
            _collection.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(_collection_CollectionChanged);
        }

        void _collection_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            if (_update.Count > 0)
            {
                List<T> newItems = new List<T>();
                List<T> oldItems = new List<T>();
                if (e.NewItems != null)
                {
                    foreach (var newItem in e.NewItems)
                    {
                        newItems.Add((T)newItem);
                    }
                }

                if (e.OldItems != null)
                {
                    foreach (var oldItem in e.OldItems)
                    {
                        oldItems.Add((T)oldItem);
                    }
                }

                JUpdateEventArgs<T> arg = new JUpdateEventArgs<T>();
                arg.Action = e.Action;
                arg.NewItems = newItems;
                arg.NewStartingIndex = e.NewStartingIndex;
                arg.OldItems = oldItems;
                arg.OldStartingIndex = e.OldStartingIndex;

                foreach (var @event in _update)
                {
                    @event(this, arg);
                }
            }
            //if (JCollectionChanged != null)
            //{
            

            //    JCollectionChanged(this, arg);
            //}
        }

        public void Add(T jModel)
        {
            _collection.Add(jModel);
        }

        public void Remove(T jModel)
        {
            _collection.Remove(jModel);
        }

        public T Get(Guid id)
        {
            foreach (var item in _collection)
            {
                if (item.Id == id)
                {
                    return item;
                }
            }
            return null;
        }

        public List<T> ToList()
        {
            return _collection.ToList();
        }

        public void Register(JContainerUpdate<T> update)
        {
            _update.Add(update);
        }
    }
}
